<#include "/macro_.ftl">
MERGE INTO ${entityMapper.tableName} A USING
(SELECT
<${r"#"}assign prefixName = true>
<#list entityMapper.fieldMapperMap?values as fieldMapper>
<${r"#"}if (index_${fieldMapper.code}??)>
${r"${prefixName?string('', ', ')}"} :index_${fieldMapper.code}_value AS ${fieldMapper.columnName}
<${r"#"}assign prefixName = false>
</${r"#"}if>
</#list> FROM DUAL) B
ON (
<${r"#"}assign prefixName = true>
<#list entityMapper.fieldMapperMap?values as fieldMapper>
<${r"#"}if (index_${fieldMapper.code}??)>
${r"${prefixName?string('', 'AND ')}"}A.${fieldMapper.columnName} = B.${fieldMapper.columnName}
<${r"#"}assign prefixName = false>
</${r"#"}if>
</#list>)
WHEN MATCHED THEN UPDATE SET
<${r"#"}assign prefixName = true>
<#list entityMapper.fieldMapperMap?values as fieldMapper>
<${r"#"}if (update_${fieldMapper.code}??)>
${r"${prefixName?string('', ', ')}"}A.${fieldMapper.columnName} = :update_${fieldMapper.code}_value
<${r"#"}assign prefixName = false>
</${r"#"}if>
</#list>
WHEN NOT MATCHED THEN INSERT
(<${r"#"}assign prefixName = true>
<#list entityMapper.fieldMapperMap?values as fieldMapper>
<${r"#"}if (insert_${fieldMapper.code}??) && (insert_${fieldMapper.code}_value??)>
${r"${prefixName?string('  ', ', ')}"}A.${fieldMapper.columnName}
<${r"#"}assign prefixName = false>
</${r"#"}if>
</#list>)
VALUES
(<${r"#"}assign prefixName = true>
<#list entityMapper.fieldMapperMap?values as fieldMapper>
<${r"#"}if (insert_${fieldMapper.code}??) && (insert_${fieldMapper.code}_value??)>
${r"${prefixName?string('  ', ', ')}"}:insert_${fieldMapper.code}_value
<${r"#"}assign prefixName = false>
</${r"#"}if>
</#list>)

